package com.huiren.util;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XMLUtil {
	private SAXReader saxReader = null;
	private Document document = null;
	private String path = "./config/sqlconfig.xml";

	public XMLUtil() {
		saxReader = new SAXReader();
		try {
			document = saxReader.read(new File(path));
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

	public List<String> selectNodes(String nodepath) {
		List<String> list = new ArrayList<String>();
		List<Element> nodes = document.selectNodes(nodepath);
		Iterator<Element> iter = nodes.iterator();
		while (iter.hasNext()) {
			Element ownerElement = (Element) iter.next();
			list.add(ownerElement.getText());
		}
		return list;

	}

	public static void main(String args[]) {
		XMLUtil xmlUtil = new XMLUtil();
		List<String> list = xmlUtil.selectNodes("/sql/defaultInsert");
		for (String str : list)
			System.out.println(str);
	}

	public static Document createXML(List objects, String rootName,
			String nodeName) throws IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement(rootName);
		for (Object object : objects) {
			Element node = root.addElement(nodeName);
			Method[] methods = object.getClass().getMethods();
			for (Method method : methods) {
				if (method.getName().startsWith("get")) {
					String text = method.getName().replaceAll("get", "")
							.toUpperCase();
					String value = method.invoke(object) == null ? "" : String
							.valueOf(method.invoke(object));
					node.addElement(text).setText(value);
				}
			}
		}
		doc.setXMLEncoding("GBK");
		return doc;
	}

}
